﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Configuration;
using UFC.Common;
using UFC.DBUtility;


namespace MESMaterialToolsAuxMaterial
{
   public class SendMaterialToolsAuxMaterialToErp
    {
       public void RunMaterialToolsAuxMaterialSync()
       {
           DataTable mydt = GetMaterialToolsAuxMaterialRecord();
           if (mydt == null || mydt.Rows.Count <= 0)
           {
               LogHelp.WriteLog("没有可处理的物料，工装，辅材配送提醒记录");
           }

           foreach (DataRow row in mydt.Rows)
           {
               var strList = GetDictionary(row);
               string strXML = CreateXMLForMaterialToolsAuxMaterialToErp(strList);
               LogHelp.WriteLog(strXML);
               string resXML = @"<?xml version='1.0' encoding='UTF-8'?><root><success>1</success><message>接收数据成功</message></root>";//调用Qms接口地址方法
               XmlDocument myxml = new XmlDocument();
               myxml.LoadXml(resXML);
               string success = myxml.SelectSingleNode("root/success").InnerText;//
               string message = myxml.SelectSingleNode("root/message").InnerText;//
               if (!string.IsNullOrWhiteSpace(success) && success == "1")
               {
                   UpdateMaterialToolsAuxMaterialRecord(row["ID"].ToString());
               }
               else
               {
                   LogHelp.WriteLog(message);
               }
           }
       }

       public DataTable GetMaterialToolsAuxMaterialRecord() {
           try
           {
               string strSql = @"SELECT ztt.ZSREQUIREDTOOLSTRANSPORTID ID
                            ,DECODE(cl.CUTTOOLNAME,NULL,DECODE(s.SPECIALTOOLNAME,NULL,m.MEASURETOOLNAME,s.SPECIALTOOLNAME),cl.CUTTOOLNAME) MaterialCode
                            --,DECODE(cl.DRAWINGNO,NULL,DECODE(s.DRAWINGNO,NULL,m.DRAWINGNO,s.DRAWINGNO),cl.DRAWINGNO) DRAWINGNO
                            --,DECODE(cl.DESCRIPTION ,NULL,DECODE(s.DESCRIPTION,NULL,m.DESCRIPTION,s.DESCRIPTION),cl.DESCRIPTION) DESCRIPTION
                            --,DECODE(cl.SPECIFICATION,NULL,DECODE(s.SPECIFICATION,NULL,m.SPECIFICATION,s.SPECIFICATION),cl.SPECIFICATION) SPECIFICATION
                            ,DECODE(cl.CUTTOOLNAME,NULL,DECODE(s.SPECIALTOOLNAME,NULL,'夹模具','量具'),'刀具') ToolTYPE
                            ,tc.QTY 
                            FROM ZsRequiredToolsTransport ztt
                            LEFT JOIN ZsRTTransportChild tc ON tc.ZSREQUIREDTOOLSTRANSPORTID =ztt.ZSREQUIREDTOOLSTRANSPORTID 
                            LEFT JOIN CUTTOOL cl ON cl.CUTTOOLID =tc.TOOLID 
                            LEFT JOIN SPECIALTOOL s ON s.SPECIALTOOLID =tc.TOOLID
                            LEFT JOIN MEASURETOOL m ON m.MEASURETOOLID=tc.TOOLID
                            WHERE ztt.TransportType='1' AND nvl(ztt.ISSENDERP,0)=0
                            UNION ALL
                            SELECT ztt.ZSREQUIREDTOOLSTRANSPORTID ID,a.AUXMATERIALNAME MaterialCode,'辅材' ToolTYPE,tc.QTY--a.DESCRIPTION,a.SPECIFICATION
                            FROM ZsRequiredToolsTransport ztt
                            LEFT JOIN ZsRTTransportChild tc ON tc.ZSREQUIREDTOOLSTRANSPORTID =ztt.ZSREQUIREDTOOLSTRANSPORTID 
                            LEFT JOIN AUXMATERIAL a ON a.AUXMATERIALID =tc.TOOLID 
                            WHERE ztt.TransportType='2' AND nvl(ztt.ISSENDERP,0)=0
                            UNION ALL
                            SELECT ISSUEMATERIALTRANSPORTID ID,PRODUCTNAME MaterialCode,'物料' ToolTYPE,APPLYQTY QTY FROM IssueMaterialTransport ztt WHERE nvl(ztt.ISSENDERP,0)=0";
               DataSet myDS = OracleHelper.Query(strSql);
               if (myDS == null)
               {
                   return null;
               }
               if (myDS.Tables.Count == 0)
               {
                   return null;
               }
               return myDS.Tables[0];
           }
           catch (Exception e)
           {
               LogHelp.WriteError("物料，工装，辅材配送提醒获取", e);
               return null;
           }
       }

       private Dictionary<string, string> GetDictionary(DataRow row)
       {
           var strList = new Dictionary<string, string>();
           var keys = "ID,MaterialCode,Qty";
           foreach (var key in keys.Split(','))
           {
               if (row.Table.Columns.Contains(key))
               {
                   strList.Add(key, row[key].ToString());
               }
               else
               {
                   strList.Add(key, "");
               }
           }
           return strList;
       }

       /// <summary>
       /// 创建xml
       /// </summary>
       /// <param name="strList"></param>
       /// <returns></returns>
       private string CreateXMLForMaterialToolsAuxMaterialToErp(Dictionary<string, string> strList)
       {
           try
           {
               XmlDocument doc = new XmlDocument();
               doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", ""));
               XmlNode ReqNode = doc.CreateElement("ReqMsg");
               XmlNode headerNode = doc.CreateElement("header");
               XmlNode senderNode = doc.CreateElement("sendSysName");
               senderNode.InnerText = "APP_MES";
               XmlNode rcvNode = doc.CreateElement("rcvSysName");
               senderNode.InnerText = "APP_ERP";

               headerNode.AppendChild(senderNode);
               headerNode.AppendChild(rcvNode);
               ReqNode.AppendChild(headerNode);
               XmlNode documentNode = doc.CreateElement("document");
               string strData = "";
               foreach (KeyValuePair<string, string> _key in strList)
               {
                   strData = string.Format("{0}<{1}>{2}</{1}>", strData, _key.Key, _key.Value);
               }
               documentNode.AppendChild(doc.CreateCDataSection(strData));
               ReqNode.AppendChild(documentNode);
               doc.AppendChild(ReqNode);
               return doc.InnerXml;
           }
           catch (Exception e)
           {
               LogHelp.WriteError("物料，工装，辅材配送提醒XML", e);
               return string.Empty;
           }
       }

       /// <summary>
       /// 发送成功，更新字段--IsSendErp（Null/0未推送,1已推送）
       /// </summary>
       private void UpdateMaterialToolsAuxMaterialRecord(string ID)
       {
           try
           {
               var arr = new System.Collections.ArrayList();
               string updateSql = string.Format(@"UPDATE ZsRequiredToolsTransport SET IsSendErp='1' WHERE ZSREQUIREDTOOLSTRANSPORTID='{0}' ", ID);
               string updateSql2 = string.Format(@"UPDATE IssueMaterialTransport SET IsSendErp='1' WHERE ISSUEMATERIALTRANSPORTID='{0}' ", ID);
               arr.Add(updateSql);
               arr.Add(updateSql2);
               OracleHelper.ExecuteSqlTran(arr);
           }
           catch (Exception ex)
           {
               LogHelp.WriteLog("临时物料，工装，辅材配送提醒更新失败：" + ex.Message);
           }
       }
   
   
   }
}
